var serverAddress = "http://127.0.0.1:9092";
var userId = "1003";
var socket;
$(function () {
    //connectMessageSocket(serverAddress,userId);
    // 初始化服务器地址和用户标识
    initSocketAddress();
    /*//while (true) {
        if (serverAddress.length > 0 && userId.length > 0) {
            connectMessageSocket(serverAddress,userId);
            //return;
        } else {
            // 容错
            initSocketAddress();
        }
    //}*/
})

var connectMessageSocket = function (serverAddress,userId) {
    var url = serverAddress + "?userId=" + userId;
    socket = io.connect(url);
    /**
     * 连接服务器
     */
    socket.on('connect', function () {
        output('<span class="connect-msg">Client has connected to the server!</span>');
    });

    /**
     * 消息发送成功回调
     */
    socket.on('sendMsgSuccessEvent', function (data) {
        output('<span class="username-msg">Client：</span> ' + data.url);
    });

    /**
     * 断开服务器
     */
    socket.on('disconnect', function () {
        output('<span class="disconnect-msg">The client has disconnected!</span>');
    });

    /**
     * 接受服务端消息
     */
    socket.on('receiveMsgEvent', function (data) {
        // 收到消息 标识小红点
        console.log();
        $("#messageSpan").addClass("layui-badge");
        $("#messageSpan").text(data.count);
        //alert(data.url);
    });

    /**
     * 断开连接
     */
    function sendDisconnect() {
        socket.disconnect();
    }
}

/**
 * 发送消息
 */
function sendMessage() {
    var message = $('#msg').val();
    $('#msg').val('');
    var jsonObject = {
        url: message
    };
    socket.emit('sendMsgEvent', jsonObject);
}

/**
 * 输出
 * @param message
 */
function output(message) {
    var currentTime = "<span class='time'>" + new Date() + "</span>";
    var element = $("<div>" + currentTime + " " + message + "</div>");
    ////console.log(new Date() + " " + currentTime + " " + message);
    $('#console').prepend(element);
}

/**
 * 回车事件
 */
$(document).keydown(function (e) {
    if (e.keyCode == 13) {
        $('#send').click();
    }
});

// 初始化服务器地址
var initSocketAddress = function (serverAddress,userId) {
    $.axsefalse(hostUrl + "/message/initSocketAddress",
        null,
        function (res) {
            if(res.status == 0) {
                var data = res.data;
                serverAddress = data.serverAddress;
                userId = data.userId;
                connectMessageSocket(serverAddress,userId);
            } else {
                //Layer.showFailAlert(res.msg);
            }
        },
        function () {
            Layer.showFailAlert("初始化消息请求失败！");
        })
}
